package com.example.demo.controller;

import com.example.demo.model.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/api/upload")
public class UploadController {

    private final String uploadDir = "uploads";

    public UploadController() {
        // 确保上传目录存在
        File directory = new File(uploadDir);
        if (!directory.exists()) {
            directory.mkdir();
        }
    }

    @PostMapping
    @ResponseBody
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, 
                                       @AuthenticationPrincipal User user,
                                       HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "文件不能为空");
                return ResponseEntity.badRequest().body(error);
            }

            // 获取文件名并生成唯一的文件名
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            String uniqueFileName = UUID.randomUUID().toString() + 
                    (fileName.contains(".") ? "." + fileName.substring(fileName.lastIndexOf(".") + 1) : "");

            // 保存文件
            Path path = Paths.get(uploadDir + File.separator + uniqueFileName);
            Files.copy(file.getInputStream(), path);

            Map<String, String> response = new HashMap<>();
            response.put("id", uniqueFileName);
            response.put("fileName", fileName);
            response.put("fileType", file.getContentType());
            response.put("url", "/uploads/" + uniqueFileName);
            response.put("size", String.valueOf(file.getSize()));

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    @GetMapping("/list")
    @ResponseBody
    public ResponseEntity<List<Map<String, String>>> listUploadedFiles() {
        try {
            // 获取上传目录中的所有文件
            File directory = new File(uploadDir);
            File[] files = directory.listFiles((dir, name) -> {
                String lowerCaseName = name.toLowerCase();
                return lowerCaseName.endsWith(".jpg") || 
                       lowerCaseName.endsWith(".jpeg") || 
                       lowerCaseName.endsWith(".png") || 
                       lowerCaseName.endsWith(".gif") || 
                       lowerCaseName.endsWith(".webp");
            });
            
            if (files == null) {
                return ResponseEntity.ok(Collections.emptyList());
            }
            
            // 构建文件信息列表
            List<Map<String, String>> filesList = Arrays.stream(files)
                .map(file -> {
                    Map<String, String> fileInfo = new HashMap<>();
                    fileInfo.put("id", file.getName().replaceFirst("[.][^.]+$", ""));
                    fileInfo.put("filename", file.getName());
                    fileInfo.put("size", String.valueOf(file.length()));
                    return fileInfo;
                })
                .collect(Collectors.toList());
            
            return ResponseEntity.ok(filesList);
        } catch (Exception e) {
            return ResponseEntity.ok(Collections.emptyList());
        }
    }
} 